<template>
	<view class="user-edit-container">
		<!-- 顶部导航栏 -->
		<!-- 	<view class="navbar">
			<view class="navbar-left" @click="onCancel">
				<i class="iconfont icon-arrow-left"></i>
			</view>
			<view class="navbar-title">编辑资料</view>
			<view class="navbar-right" @click="onSave" :class="{ disabled: !formValid }">
				保存
			</view>
		</view> -->

		<!-- 用户头像 -->
		<view class="avatar-container">
			<view class="avatar-wrapper">
				<image :src="form.avatar" class="avatar" mode="cover"></image>
				<view class="avatar-upload" @click="chooseAvatar">
					<i class="iconfont icon-camera"></i>
				</view>
			</view>
			<view class="avatar-tip">点击更换头像</view>
		</view>

		<!-- 表单内容 -->
		<form class="form-container">
			<!-- 用户名 -->
			<view class="form-item">
				<view class="form-label">姓名</view>
				<input class="form-input" type="text" v-model="form.username" placeholder="请输入姓名" maxlength="16"
					@input="validateUsername" />
			</view>
			<view class="error-message" v-if="errors.username">{{ errors.username }}</view>

			<!-- 手机号码 -->
			<view class="form-item">
				<view class="form-label">手机</view>
				<input class="form-input" type="number" v-model="form.phone" placeholder="请输入手机号码" maxlength="11"
					@input="validatePhone" />
			</view>
			<view class="error-message" v-if="errors.phone">{{ errors.phone }}</view>

			<!-- 邮箱 -->
			<view class="form-item">
				<view class="form-label">邮箱</view>
				<input class="form-input" type="text" v-model="form.email" placeholder="请输入邮箱地址"
					@input="validateEmail" />
			</view>
			<view class="error-message" v-if="errors.email">{{ errors.email }}</view>

			<!-- 性别 -->
			<view class="form-item">
				<view class="form-label">性别</view>
				<view class="gender-selector">
					<view class="gender-option" :class="{ selected: `${form.sex}` === '1' }"
					 @click="form.sex = '1'">
						男
					</view>
					<view class="gender-option" :class="{ selected: `${form.sex}` === '2' }"
						@click="form.sex = '2'">
						女
					</view>
					<view class="gender-option" :class="{ selected: `${form.sex}` === '3' }"
						@click="form.sex = '3'">
						保密
					</view>
				</view>
			</view>

			<!-- 公司名 -->
			<view class="form-item">
				<view class="form-label">公司</view>
				<input class="form-input" type="text" v-model="form.companyName" placeholder="请输入公司名称" maxlength="16"
					@input="validateCompanyName" />
			</view>
			<!--行业-后面做成可选的-->
			<view class="form-item">
				<view class="form-label">行业</view>
				<input class="form-input" type="text" v-model="form.postText" placeholder="请输入行业" maxlength="16"
					@input="validateUsername" />
			</view>
			<view class="error-message" v-if="errors.postText">{{ errors.postText }}</view>
			<view class="error-message" v-if="errors.companyName">{{ errors.companyName }}</view>

			<!-- 职位 -->
			<view class="form-item">
				<view class="form-label">职位</view>
				<input class="form-input" type="text" v-model="form.position" placeholder="请输入职位" maxlength="16"
					@input="validatePosition" />
			</view>
			<view class="error-message" v-if="errors.position">{{ errors.position }}</view>
			<!--地址-->
			<view class="form-item">
				<view class="form-label">地址</view>
				<input class="form-input" type="text" v-model="form.companyAddress" placeholder="请输入地址" maxlength="16"
					@input="validateUsername" />
			</view>
			<view class="error-message" v-if="errors.companyAddress">{{ errors.companyAddress }}</view>
		</form>

		<!-- 底部操作区 -->
		<view class="delete-account" @click="onSave">
			<i class="iconfont icon-trash"></i>
			<text>保存</text>
		</view>
		<!-- 加载提示 -->
		<view class="loading-toast" v-if="isLoading">
			<view class="loading-spinner"></view>
			<view class="loading-text">{{ loadingText }}</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed
	} from 'vue'
	import {
		http
	} from '@/utils/http'
	import {
		useUserStore
	} from '@/store/user'
	const userStore = useUserStore()
	// 接收页面参数
	// const props = defineProps({
	// 	userId: {
	// 		type: [String, Number],
	// 		required: true
	// 	}
	// })

	// 表单数据
	const form = ref({
		id: 0,
		avatar: 'https://picsum.photos/200/200?random=1',
		username: '',
		phone: '',
		email: '',
		sex: 'unknown',
		companyName: '',
		position: '',
		companyAddress: ''
	})

	// 错误信息
	const errors = ref({
		username: '',
		phone: '',
		email: '',
		companyName: '',
		postText: '',
		position: ''
	})

	// 状态管理
	const isLoading = ref(false)
	const loadingText = ref('加载中...')

	// 表单验证状态
	const formValid = computed(() => {
		return !Object.values(errors).some(error => error !== '') &&
			form.username.trim() !== ''
	})

	// 页面加载时获取用户信息
	onShow(() => {
		fetchUserInfo(userStore.userInfo.id)
	})

	// 获取用户信息
	const fetchUserInfo = (userId) => {
		isLoading.value = true
		loadingText.value = '加载中...'
		http.get(`/chamber/ccUser/queryById?id=` + userId).then((res) => {
				if (res.success) {				
					form.value = res.result
				} else {
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					})
				}
			})
			.catch((err) => {
				console.error('获取用户信息错误:', err)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			}).finally(() => {
				isLoading.value = false
			})
	}

	// 选择头像
	const chooseAvatar = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				const tempFilePath = res.tempFilePaths[0]
				form.avatar = tempFilePath
			},
			fail: (err) => {
				console.error('选择头像失败:', err)
			}
		})
	}

	// 表单验证方法
	const validateUsername = () => {
		if (!form.username) {
			errors.username = '姓名不能为空'
		} else if (form.username.length < 2) {
			errors.username = '姓名至少2个字符'
		} else {
			errors.username = ''
		}
	}

	const validatePhone = () => {
		const phoneReg = /^1[3-9]\d{9}$/
		if (form.phone && !phoneReg.test(form.phone)) {
			errors.phone = '请输入正确的手机号码'
		} else {
			errors.phone = ''
		}
	}

	const validateEmail = () => {
		const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
		if (form.email && !emailReg.test(form.email)) {
			errors.email = '请输入正确的邮箱地址'
		} else {
			errors.email = ''
		}
	}

	const validateCompanyName = () => {
		if (form.companyName && form.companyName.length > 16) {
			errors.companyName = '公司名称不能超过16个字符'
		} else {
			errors.companyName = ''
		}
	}

	const validatePosition = () => {
		if (form.position && form.position.length > 16) {
			errors.position = '职位不能超过16个字符'
		} else {
			errors.position = ''
		}
	}

	// 保存用户信息
	const onSave = async () => {
		console.log(form)
		try {
			isLoading.value = true
			loadingText.value = '保存中...'
			const params = form.value
			const res = await http.post('/chamber/ccUser/edit', params)
			console.log(res)
			if (res.success) {
				uni.showToast({
					title: '保存成功',
					icon: 'success',
					duration: 2000
				})

				// 保存成功后返回上一页
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} else {
				uni.showToast({
					title: res.message || '保存失败',
					icon: 'none'
				})
			}
		} catch (err) {
			console.error('保存失败:', err)
			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			})
		} finally {
			isLoading.value = false
		}
	}

	// 取消编辑
	const onCancel = () => {
		uni.navigateBack()
	}
</script>

<style scoped>
	/* 基础样式 */
	.user-edit-container {
		min-height: 100vh;
		background-color: #f5f5f5;
		font-size: 16px;
	}

	/* 导航栏 */
	.navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 44px;
		padding: 0 16px;
		background-color: #fff;
		border-bottom: 1px solid #eee;
	}

	.navbar-left,
	.navbar-right {
		width: 50px;
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.navbar-title {
		flex: 1;
		text-align: center;
		font-weight: 500;
	}

	.navbar-right {
		color: #07c160;
		font-size: 16px;
	}

	.navbar-right.disabled {
		color: #ccc;
	}

	/* 头像区域 */
	.avatar-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 24px 0;
		background-color: #fff;
		margin-bottom: 10px;
	}

	.avatar-wrapper {
		position: relative;
		width: 100px;
		height: 100px;
		border-radius: 50%;
		overflow: hidden;
		margin-bottom: 12px;
	}

	.avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-upload {
		position: absolute;
		bottom: 0;
		right: 0;
		width: 30px;
		height: 30px;
		background-color: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #fff;
	}

	.avatar-tip {
		font-size: 14px;
		color: #666;
	}

	/* 表单样式 */
	.form-container {
		background-color: #fff;
		margin-bottom: 10px;
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 0 16px;
		height: 50px;
		border-bottom: 1px solid #eee;
	}

	.form-item:last-child {
		border-bottom: none;
	}

	.form-label {
		width: 80px;
		color: #333;
	}

	.form-input {
		flex: 1;
		height: 100%;
		padding: 0;
		border: none;
		outline: none;
		font-size: 16px;
		color: #333;
	}

	.form-input::placeholder {
		color: #ccc;
	}

	/* 性别选择 */
	.gender-selector {
		flex: 1;
		display: flex;
		gap: 10px;
	}

	.gender-option {
		padding: 5px 15px;
		border-radius: 20px;
		font-size: 14px;
		background-color: #f5f5f5;
	}

	.gender-option.selected {
		background-color: #07c160;
		color: #fff;
	}

	/* 错误信息 */
	.error-message {
		padding: 0 16px 8px;
		font-size: 12px;
		color: #ff4d4f;
		background-color: #fff;
	}

	/* 加载提示 */
	.loading-toast {
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 120px;
		height: 120px;
		background-color: rgba(0, 0, 0, 0.7);
		border-radius: 10px;
		color: #fff;
		z-index: 1002;
	}

	.loading-spinner {
		width: 40px;
		height: 40px;
		border: 3px solid rgba(255, 255, 255, 0.3);
		border-radius: 50%;
		border-top-color: #fff;
		animation: spin 1s ease-in-out infinite;
		margin-bottom: 10px;
	}

	.loading-text {
		font-size: 14px;
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}

	/* 删除账号 */
	.delete-account {
		display: flex;
		align-items: center;
		justify-content: center;
		color: #ff4d4f;
		padding: 16px;
		background-color: #fff;
		margin-top: 10px;
	}

	.delete-account icon {
		margin-right: 5px;
	}
</style>